package io.renren.common.exception;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.renren.common.constant.CommonCode;
import io.renren.common.constant.MsgCode;
import io.renren.common.msg.Response;
import io.renren.common.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.Collections;
import java.util.Optional;

/**
 * ClassName: GlobalExceptionHandler
 *
 * @author M on 2021/5/16 20:36
 * version    V1.0
 */
@Slf4j
@ConditionalOnClass({HttpServletRequest.class, HttpServletResponse.class})
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    @ExceptionHandler({Exception.class})
    Object serverExceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception e) {
        MsgCode msgCode;
        BaseException baseException = null;
        if (isJson(request)) {
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            Response result;
            if (e instanceof BaseException) {
                baseException = (BaseException) e;
                msgCode = baseException.getMsgCode();
                result = ResponseUtil.fail(Collections.EMPTY_MAP, msgCode, baseException.getMessage());
            } else if (e instanceof HttpMessageNotReadableException) {
                result = ResponseUtil.fail(Collections.EMPTY_MAP, "缺少必须的参数");
            } else if (e instanceof HttpMediaTypeNotSupportedException) {
                result = ResponseUtil.fail(Collections.EMPTY_MAP, "请求类型不匹配");
            } else if (e instanceof HttpRequestMethodNotSupportedException) {
                result = ResponseUtil.fail(Collections.EMPTY_MAP, "不支持该类型的请求");
            } else if (e instanceof MethodArgumentNotValidException) {
                result = ResponseUtil.fail(Collections.EMPTY_MAP, ((MethodArgumentNotValidException) e).getBindingResult().getFieldError().getDefaultMessage());
            } else if (e instanceof BindException) {
                result = ResponseUtil.fail(Collections.EMPTY_MAP, ((BindException) e).getBindingResult().getFieldError().getDefaultMessage());
            } else if (e instanceof ConnectException) {
                result = ResponseUtil.fail(Collections.EMPTY_MAP, CommonCode.OPER_BASE_FAILD);
            } else if (e instanceof IllegalStateException || e instanceof ResourceAccessException || e instanceof SocketTimeoutException) {
                result = ResponseUtil.fail(Collections.EMPTY_MAP, CommonCode.SERVICE_UPGRADING);
            } else {
                result = ResponseUtil.fail(Collections.EMPTY_MAP, CommonCode.OPER_BASE_FAILD);
            }
            log.error("异常信息:{}", Optional.ofNullable(baseException).filter(e1 -> e1.getMsgCode() != null).map(b -> b.getMsgCode().getMessage()).orElse(e.getMessage()));
            e.printStackTrace();
            try (PrintWriter printWriter = response.getWriter()) {
                printWriter.write(OBJECT_MAPPER.writeValueAsString(result));
            } catch (IOException e1) {
            }
        } else {
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            Response result;
            if (e instanceof BaseException) {
                baseException = (BaseException) e;
                msgCode = baseException.getMsgCode();
                result = ResponseUtil.fail(Collections.EMPTY_MAP, msgCode, baseException.getMessage());
            } else if (e instanceof MaxUploadSizeExceededException) {
                result = ResponseUtil.fail(Collections.EMPTY_MAP, "请不要上传超过100MB的文件");
            } else if (e instanceof MultipartException) {
                result = ResponseUtil.fail(Collections.EMPTY_MAP, "缺少上传文件");
            } else if (e instanceof MissingServletRequestParameterException) {
                result = ResponseUtil.fail(Collections.EMPTY_MAP, "缺少请求参数");
            } else {
                result = ResponseUtil.fail(Collections.EMPTY_MAP, CommonCode.OPER_BASE_FAILD);
            }
            log.error("异常信息:{}", Optional.ofNullable(baseException).filter(e1 -> e1.getMsgCode() != null).map(b -> b.getMsgCode().getMessage()).orElse(e.getMessage()));
            e.printStackTrace();
            try (PrintWriter printWriter = response.getWriter()) {
                printWriter.write(OBJECT_MAPPER.writeValueAsString(result));
            } catch (IOException e1) {
            }
        }
        return null;
    }

    /**
     * 判断请求是否是json
     *
     * @param request
     * @return
     */
    private Boolean isJson(HttpServletRequest request) {
        String header = request.getHeader("content-type");
        return header != null && header.contains("json");
    }
}
